package 二叉树题目.序列化二叉树;

public class Solution {
    public static int i = 0;

    public String Serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        StringBuilder sb = new StringBuilder();
        SerializeFunc(root, sb);
        return sb.toString();
    }

    public static void SerializeFunc(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("#");
            return;
        }
        sb.append(root.val).append("!");
        // 处理左子树
        SerializeFunc(root.left, sb);
        // 处理右子树
        SerializeFunc(root.right, sb);
    }

    public TreeNode Deserialize(String str) {
        if (str == "#"){
            return null;
        }
        return DeserializeFunc(str);

    }

    public static TreeNode DeserializeFunc(String str) {
        // 碰到#表示空节点
        if (str.charAt(i) == '#') {
            i++;
            return null;
        }
        // 字符转换数字
        int val = 0;

        // 此时遇到的不是分隔符或者是结尾
        while (str.charAt(i) != '!' && i != str.length()){
            val = val * 10 + ((str.charAt(i)) - '0');
            i++;
        }
        TreeNode root = new TreeNode(val);
        if(i == str.length()){
            return root;
        }else {
            i++;
        }
        root.left = DeserializeFunc(str);
        root.right = DeserializeFunc(str);
        return root;
    }
}
